﻿using System.Xml;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;


namespace 开发自己的配置提供者;

public class MyConfigProvider : FileConfigurationProvider
{
    public MyConfigProvider(FileConfigurationSource source) : base(source)
    {
        
    }

    public override void Load(Stream stream)
    {
        var data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        var xmlDoc = new XmlDocument();
        xmlDoc.Load(stream);
        //获取connectionStrings配置
        using (XmlNodeList xmlNodeList = xmlDoc.SelectNodes("/configuration/connectionStrings/add"))
        {
            if (xmlNodeList.Count <= 0)
            {
                return;
            }

            foreach (var xmlNode in xmlNodeList.Cast<XmlNode>())
            {
                var name = xmlNode.Attributes["name"].Value;
                var connectStr = xmlNode.Attributes["connectionString"].Value;
                var providerName = xmlNode.Attributes["providerName"].Value;
                data.Add($"{name}:connectionString",connectStr);
                if(!string.IsNullOrEmpty(providerName))
                {
                    data.Add($"{name}:providerName",providerName);
                }
            }
        }
        //获取APPSettings配置
        using (XmlNodeList xmlNodeList = xmlDoc.SelectNodes("/configuration/appSettings/add"))
        {
            if (xmlNodeList.Count<=0)
            {
                return;
            }

            foreach (var xmlNode in xmlNodeList.Cast<XmlNode>())
            {
                string key = xmlNode.Attributes["key"].Value;
                key = key.Replace('.', ':');
                string value = xmlNode.Attributes["value"].Value;
                data.Add(key,value);
            }
        }

        this.Data = data;
    }
}